package cn.com.jsepc.rep.report;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import net.sf.json.JSONArray;
import cn.com.jsepc.rep.comm.ConstUtil;
import cn.com.jsepc.rep.demension.CheckLeaf;
import cn.com.jsepc.rep.demension.DementionDAO;
import cn.com.jsepc.rep.vo.DemTreeVO;

import com.jarp.db.DAO;

public class CorpDeptTree {
	
	public String getCorpDeptTreeData(String parentid,String corpid) {
        String res = "";
        JSONArray json = new JSONArray();
        StringBuffer sqls = new StringBuffer();
        List<DemTreeVO> lstResults = new ArrayList<DemTreeVO>();
        try {
            	DAO dao = new DAO();
            	sqls.append("SELECT * FROM TB_CORP_DEPT where PID='"+parentid+"'");
	            sqls.append(" order by ID ");
	            Vector v = dao.getDataSet(ConstUtil.DBNAME, sqls.toString(),0,0);
	            if (v != null) {
	                for (int i = 0; i < v.size(); i++) {
	                    Hashtable hashRows = (Hashtable)v.get(i);
	                    DemTreeVO treeVO = new DemTreeVO();
	                    treeVO.setId((String) hashRows.get("ID"));
	                    treeVO.setText((String) hashRows.get("NAME"));
	                    boolean isLeaf=this.isLeaf(treeVO.getId(), "PID", "TB_CORP_DEPT");
	                    treeVO.setLeaf(isLeaf);
	                    treeVO.setCheck(false);
	                    lstResults.add(treeVO);
	                }
	                json = JSONArray.fromObject(lstResults);
	            }
	            res = json.toString();
        } catch (ServletException ex) {
            Logger.getLogger(DementionDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return res;
    }

	public boolean isLeaf(String ID,  String parent_id_colum_name, String table_name) {
	    boolean bLeaf = false;
	    try {
	        DAO dao=new DAO();
	        String sql="SELECT count(1) CC from "+table_name+" Where "+parent_id_colum_name+"='"+ID+"'";
	        String cc=dao.getDataValue(ConstUtil.DBNAMEODS, sql);
	        if(Integer.parseInt(cc)==0)
	            bLeaf = true;
	    } catch (ServletException ex) {
	        Logger.getLogger(CheckLeaf.class.getName()).log(Level.SEVERE, null, ex);
	        
	    }
	    return bLeaf;
	}
}
